<?php
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class table_ad extends discuz_table
{
	public function __construct() {

		$this->_table ='er_gridad_combo';
		$this->_pk    = 'id';

		parent::__construct();
	}
	
	/**
	 * 获取广告列表
	 * @param int $page 页码
	 * @param int $pagesize 每页数量
	 * @return array 广告数组
	 */
	public function fetch_all($page = 1, $pagesize = 10, $uid = null, $position = null, $type = null, $sort = null ) {
		$where = array();
		$params = array($this->_table);
		
		if($uid !== null && $uid != 0) {
			$where[] = 'uid=%d';
			$params[] = $uid;
		}
		if($position !== null && $position != 0) {
			$where[] = 'position=%d'; 
			$params[] = $position;
		}
		if($type !== null && $type != 0) {
			$where[] = 'type=%d';
			$params[] = $type;
		}

		$where[] = '(expire_time IS NULL OR expire_time > %d)';
    	$params[] = TIMESTAMP;
		
		$sql = "SELECT * FROM %t";
		if(!empty($where)) {
			$sql .= " WHERE " . implode(' AND ', $where);
		}
		$sql .= " ORDER BY sort DESC";
		
		return DB::fetch_all($sql, $params);
	}
	
	/**
	 * 插入广告
	 * @param array $data 广告数据
	 * @return int 插入的广告ID
	 */
	public function insert($data, $return_insert_id = false, $replace = false, $silent = false, $unbuffered = false) {
		return DB::insert($this->_table, $data, $return_insert_id, $replace, $silent, $unbuffered);	
	}

	/**
	 * 更新广告
	 * @param int $id 广告ID
	 * @param array $data 要更新的数据
	 * @return bool 更新结果
	 */
	public function update($id, $data, $unbuffered = false, $low_priority = false) {
		return DB::update($this->_table, $data, array('id' => $id), $unbuffered, $low_priority);	
	}

	/**
     * 删除广告
     * @param int $id 广告ID
     * @param bool $unbuffered 是否无缓冲
     * @return bool 删除结果
     * @throws Exception 如果删除失败
     */
    public function delete($id, $unbuffered = false) {
        if(DB::delete($this->_table, array('id' => $id), $unbuffered)) {
            return true;
        } else {
            throw new Exception('删除广告失败');
        }
    }

	/**
	 * 审核通过
	 * @param int $id 广告ID
	 * @return bool 审核结果
	 */
	public function audit_pass($id) {
		$result = DB::update($this->_table, array('status' => 1), array('id' => $id));
		return $result ? true : false;
	}
}